package com.tledu.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * get请求传参
 */
public class HttpClient02 {
    public static void main(String[] args) throws IOException {
        // 需要知道我们请求的地址是哪一个
        // 可以直接把参数写在地址里，通过？拼接，多个参数用&分割
//        String url = "http://59.111.104.209:13000/get?name=kxr&age=18";
        String url = "http://59.111.104.209:13000/get";
        // 通过httpClient给我们提供的
        List<NameValuePair> pairList = new ArrayList<>();
        pairList.add(new BasicNameValuePair("name","cyrus"));
        pairList.add(new BasicNameValuePair("age","18"));
        url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairList), "utf-8");
        System.out.println(url);
        // 1. 创建httpClient实例
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建请求
        HttpGet httpGet = new HttpGet(url);
        // 3. 通过httpClient执行get请求,拿到请求结果
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 4. 对结果进行处理
        //  4.1 获取请求的状态码，请求状态200代表成功
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            // 请求失败了
            // 关闭这个请求
            httpGet.abort();
            System.out.println("请求异常");
        } else {
            // 请求成功
            // 5. 获取请求体
            HttpEntity entity = response.getEntity();
            // 拿到这个请求体之后，获取响应的结果
            if (entity != null) {
                // 通过这个api就可以拿到请求之后的字符串数据
                System.out.println(EntityUtils.toString(entity, "utf-8"));
                // 释放支援
                EntityUtils.consume(entity);
                // 关闭这个响应
                response.close();
            }


        }
    }
}
